<!-- 模拟考试详情 -->
<template>
  <div class="examManage-page">
    <div class="examManage-title">{{title}}</div>
    <div class="examManage-box">
      <div class="examManage-box-l">
        <div class="examManage-box-c-car">
          <div class="answerSheet-box">
            <div class="answerSheet-box-name" style="text-align: left">答题卡</div>
            <div class="answerSheet-on">
<!--              <div class="answerSheet-box-cont" v-for="item in 3">-->
              <!--  单选  -->
              <div class="answerSheet-box-cont" v-if="answerList1.length">
                <div class="theory-box-l-title">单选（共{{answerList1.length}}题，合计{{accMul(objInfo.single_number, objInfo.single_score)}}分）</div>
                <div class="answerSheet-box-cont-o">
                  <div class="answerSheet-box-cont-o-item" :class="item.answer ? 'selected' : ''" @click="positionLocation(item)" v-for="(item, index) in answerList1">
                    <div style="margin-top: 2px">{{ index + 1 }}</div>
                    <div>单</div>
                  </div>
                </div>
              </div>
              <!--  多选  -->
              <div class="answerSheet-box-cont" v-if="answerList2.length">
                <div class="theory-box-l-title">多选（共{{ answerList2.length }}题，合计{{accMul(objInfo.many_number, objInfo.many_score)}}分）</div>
                <div class="answerSheet-box-cont-o">
<!--                  <div class="answerSheet-box-cont-o-item":class="item.answer && item.answer.split(',').length>=2 ? 'selected' : ''" @click="positionLocation(item)" v-for="(item, index) in answerList2">-->
                  <div class="answerSheet-box-cont-o-item":class="item.answer ? 'selected' : ''" @click="positionLocation(item)" v-for="(item, index) in answerList2">
                    <div style="margin-top: 2px" >{{ index + 1 }}</div>
                    <div>多</div>
                  </div>
                </div>
              </div>
              <!--  判断  -->
              <div class="answerSheet-box-cont" v-if="answerList3.length">
                <div class="theory-box-l-title">判断（共{{answerList3.length}}题，合计{{accMul(objInfo.judge_number, objInfo.judge_score)}}分）</div>
                <div class="answerSheet-box-cont-o">
                  <div class="answerSheet-box-cont-o-item" :class="item.answer ? 'selected' : ''" @click="positionLocation(item)" v-for="(item, index) in answerList3">
                    <div style="margin-top: 2px">{{ index + 1 }}</div>
                    <div>判</div>
                  </div>
                </div>
              </div>
            </div>

          </div>
        </div>
      </div>
      <div class="examManage-box-c">
        <div class="examManage-box-c-car" id="chatScrollBox" style="padding-top: 10px">
          <div class="examPractice-box" v-for="(item, index) in list">
            <div class="examPractice-box-t">
              <span class="box-t-title">{{index + 1}}、【{{item.question.type_name}}】{{item.question.title}}</span>
              <!--<img src="@/assets/icon/star.png" alt="">-->
<!--              <img src="@/assets/icon/star-active.png" alt="" @click="handleFavoriteTopic(item)">-->
            </div>
            <div class="examPractice-box-c">
              <div class="box-c-exam">
                <div class="box-c-exam-item" v-for="(qitem, qindex) in item.question.option"  @click="slectAn(index, qindex)">
                  <div class="check-up" :class="{ checkActive: isSelect(item, item.answer, getIndex(qindex))}">
                    <div class="check-active-in"></div>
                  </div>
                  <div :class="{ active: isSelect(item, item.answer, getIndex(qindex))}">
                    <span class="">{{ getIndex(qindex) }}、</span>
                    <span>{{ qitem.content }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="examManage-box-r">
        <div class="examManage-box-cont">
          <div class="examManage-box-r-t">
            <img :src="userInfo.avatarUrl" alt="">
            <div class="box-r-t-line">
              <span>考生姓名：</span>
              <span>{{ userInfo.userName || '游客' + userInfo.user_id }}</span>
            </div>
            <div class="box-r-t-line">
              <span>手机号：</span>
              <span>{{ userInfo.mobile }}</span>
            </div>
            <div class="box-r-t-line">
              <span>倒计时：</span>
              <el-statistic
                  ref="statistic"
                  @finish="finishHandel"
                  format="HH:mm:ss"
                  :value="duration"
                  time-indices
              >
              </el-statistic>
            </div>
          </div>
          <div class="examManage-box-r-b">
            <div class="box-r-b-tip">注意：时间结束后，若还没答完题，系统将自动交卷。</div>
            <div class="box-r-b-btn" @click="sureClick">交 卷</div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
        title="提示"
        :show-close="false"
        :visible.sync="dialogVisible"
        width="20%"
        top="30vh"
        center
        :before-close="handleClose">
      <div style="text-align: center">确定交卷？</div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" style="border: 1px solid #0158FD; color: #0158FD;" @click="dialogVisible = false">取 消</el-button>
        <el-button size="mini" style="background: #0158FD" type="primary" @click="submitClick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import ExamPractice from '@/components/ExamPractice'
import {getSimulateDetail, getStartAnswer, getSubmitAnswer, getSubmitTheTestPaper, favoriteTopic} from "@/api";
import watermark from "@/utils/watermark";
export default {
  name: "examManage",
  components: { ExamPractice },
  data(){
    return {
      title: '', // 考试标题
      dialogVisible: false,
      Qsindex: 0,
      paperId: '', // 考试ID
      list: [], // 考试题目
      recordId: '', //
      answerList1: [], //单选
      answerList2: [], //多选
      answerList3: [], // 判断
      examInfo: {},
      duration: null,
      userInfo: {}, // 用户信息
      objInfo: {
        single_number: 0, // 单选数量
        single_score: 0, // 单选分数
        many_number: 0, // 多选数量
        many_score: 0, // 多选分数
        judge_number: 0, // 判断数量
        judge_score: 0, // 判断分数
      }
    }
  },
  mounted() {
    this.userInfo = JSON.parse(localStorage.getItem('userInfo'))
    this.paperId = this.$route.query.paper_id
    if (this.paperId) {
      // this.getDetail()
      this.getStartAnswer()
    }
    let userInfo = JSON.parse(localStorage.getItem('userInfo'))
    if (userInfo) {
      watermark.set(userInfo.userName + userInfo.user_id)
    }
  },
  methods: {
    // 考试时间到
    finishHandel() {
      this.$confirm("考试时间到！点击确定提交试卷！", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "",
        showCancelButton: false,
        type: "warning",
      }).then(() => {
        this.submitClick()
      }).catch(() => {
        this.submitClick()
        // this.$router.push({ path: '/simulatedExam' })
      });
    },
    // 位置定位
    positionLocation(item) {
      // 获取id
      let id = item.question_id
      const index = this.list.findIndex(item => item.question_id == id)
      const childs = document.querySelectorAll(".examPractice-box");
      const scrollHeight = childs[index].offsetTop
      let div = document.getElementById("chatScrollBox");
      div.scrollTop = scrollHeight - 100
    },
    // 获取模拟考试题目
    getDetail() {
      let params = {
        paper_id: this.paperId
      }
      getSimulateDetail(params).then(res=> {
        this.title = res.data.detail.paper.title
        this.duration = Date.now() + 1000 * 60 * res.data.detail.paper.exam_time
        this.list = res.data.detail.question.map((item)=> {
          return {
            ...item,
            answer: ''
          }
        })
      })
    },


    // 答题卡
    getStartAnswer(e) {
      let params = {
        paper_id: this.paperId,
      }
      getStartAnswer(params).then(res=> {
        let arr = res.data.detail.question || []
        this.title = res.data.detail.paper.title
        this.duration = Date.now() + 1000 * 60 * res.data.detail.paper.exam_time
        Object.keys(this.objInfo).map(item => {
          this.objInfo[item] = res.data.detail.paper[item]
        })
        this.list = arr.map((item)=> {
          return {
            ...item
          }
        })
        if (arr.length > 0) {
          this.answerList1 = []
          this.answerList2 = []
          this.answerList3 = []
          arr.forEach((item) => {
            if (item.question.question_type == 1) {
              this.answerList1.push(item)
            }
            if (item.question.question_type == 2) {
              this.answerList2.push(item)
            }
            if (item.question.question_type == 3) {
              this.answerList3.push(item)
            }
          })
        }
        this.recordId = res.data.detail.record_id
      })
    },
    // 提交校验
    sureClick() {

      this.dialogVisible = true
      // let arrList = []
      // let indexList = []
      // this.list.forEach((item, index) => {
      //   if (item.question_type == 2 && item.answer.split(',').length < 2) {
      //     arrList.push(item)
      //     indexList.push(index+1)
      //
      //   }
      // })
      // if (arrList.length > 0) {
      //   this.$message.warning(indexList.join(",") + '多选题至少选择两个选项！')
      // } else {
      //   this.dialogVisible = true
      // }

    },
    // 点击每题答案提交
    subAnser() {
      // let itemInfo = this.list[this.Qsindex]
      let answer = this.list[this.Qsindex].answer;
      // let arr = this.list[this.Qsindex].answer.split(',')
      if (!answer) {
        return
      }
      // if (itemInfo.question.question_type == 2) {
      //   if (arr.length < 2) {
      //     return;
      //   }
      // }
      let id = this.list[this.Qsindex].id;
      let params = {
        id: id,
        answer: answer
      }
      getSubmitAnswer(params).then(res => {
        if (res.code == 1) {
          this.getStartAnswer()
        }
      })
    },
    handleClose() {

    },
    // 选项字母
    getIndex(n) {
      return String.fromCharCode(n + 65)
    },

    isSelect(e, answer, answer2) {
      if (e.question.question_type == 2) {
        return answer.indexOf(answer2) != -1
      } else {
        return answer === answer2
      }
    },
    slectAn(index, n) {
      this.Qsindex = index
      let item = this.list[index];
      if (item.question.question_type != 2) {
        item.answer = this.getIndex(n);
        this.subAnser();
      } else {
        let arr = item.answer || [];
        let currentOptions = this.getIndex(n);
        if (typeof arr == 'string') {
          arr = item.answer.split(',');
        }
        let arrIndex = arr.indexOf(currentOptions);
        if (arrIndex > -1) {
          arr.splice(arrIndex, 1)
        } else {
          arr.push(this.getIndex(n))
        }
        item.answer = arr.join(",")
        this.subAnser();
      }
    },
    // 收藏题目
    handleFavoriteTopic(e) {
      let params = {
        paper_id: e.paper_id,
        question_id: e.question_id,
        paper_question_id: e.paper_question_id,
      }
      favoriteTopic(params).then(res => {
        if (res.code == 1) {
          this.$message.success('收藏成功')
        }
      })
    },
    // 确认交卷
    submitClick() {
      let params = {record_id: this.recordId}
      getSubmitTheTestPaper(params).then(res => {
        this.dialogVisible = false
        this.$router.push({
          path: '/examDetails',
          query: {
            paper_id: this.paperId,
            record_id: this.recordId
          }
        })
      })
    },
    /**
     * 数字相乘
     * @param {*} a1
     * @param {*} a2
     * @returns
     */
    accMul(a1, a2) {
      var m = 0,
          s1 = a1.toString(),
          s2 = a2.toString();
      try {
        m += s1.split(".")[1].length;
      } catch (e) { }
      try {
        m += s2.split(".")[1].length;
      } catch (e) { }
      return (
          (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
          Math.pow(10, m));
    }
  }
}
</script>

<style lang="scss" scoped>
.examManage-page {
  width: 100%;
  height: 100vh;
  user-select: none;
  background: #F5F5F5;
  .examManage-title {
    width: 100%;
    height: 50px;
    line-height: 50px;
    font-weight: 500;
    font-size: 18px;
    color: #FFFFFF;
    text-align: center;
    background: #0158FD;
  }
  .examManage-box {
    width: 97%;
    height: calc(100vh - 90px);
    margin: 20px auto;
    display: flex;
    justify-content: space-between;
    .examManage-box-l {
      width: 22%;
      height: 100%;
      background: #FFFFFF;
      border-radius: 4px;
    }
    .examManage-box-c {
      width: 58%;
      height: 100%;
      background: #FFFFFF;
      border-radius: 4px;
    }
    .examManage-box-r {
      width: 17%;
      height: 100%;
      background: #FFFFFF;
      border-radius: 4px;
      overflow: hidden;
      .examManage-box-cont {
        width: 80%;
        height: calc(100% - 60px);
        margin: 30px auto;
        position: relative;
        .examManage-box-r-t {
          width: 100%;
          padding-top: 20px;
          img {
            display: block;
            width: 90px;
            height: 90px;
            margin: 0 auto 30px;
          }
          .box-r-t-line {
            margin: 15px 0 10px 0;
            font-size: 12px;
            color: rgba(51, 51, 51, 0.7);
            display: flex;
            justify-content: flex-start;
            align-items: center;
            span{
              display: inline-block;
              width: 70px;
            }
            ::v-deep .el-statistic .con .number {
              font-size: 12px;
            }
            ::v-deep .el-statistic .con {
              justify-content: normal;
              margin-left: 16px;
            }
          }

        }
        .examManage-box-r-b {
          width: 100%;
          height: 60px;
          position: absolute;
          bottom: 20px;
          left: 0;
          .box-r-b-tip {
            font-weight: 400;
            font-size: 12px;
            color: #E11300;
          }
          .box-r-b-btn {
            width: 100%;
            height: 28px;
            line-height: 28px;
            font-size: 12px;
            color: #FFFFFF;
            text-align: center;
            background: #0158FD;
            margin-top: 20px;
            border-radius: 3px;
          }
        }
      }
    }
  }

  .active {
    color: #3582E5;
  }
  .check-up {
    width: 14px;
    height: 14px;
    border-radius: 50%;
    border: 1px solid #9F9F9F;
    margin-right: 10px;
  }
  .checkActive {
    width: 14px;
    height: 14px;
    border-radius: 50%;
    border: 1px solid #9F9F9F;
    margin-right: 10px;
    .check-active-in {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      margin: 2px auto;
      background: #3582E5;
      border: 1px solid #3582E5;
    }
  }
}
</style>
